package com.ctw.tinyservices.id.sdk.util;

import com.ctw.tinyservices.id.common.constants.UrlHeaderConstants;
import com.ctw.tinyservices.id.sdk.config.IdSdkConfig;
import com.ctw.tinyservices.id.sdk.enums.MethodBaseEnum;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author TongWei.Chen 2022/3/24 21:14
 *
 * 负载均衡工具类
 **/
public final class ServerLoadBalanceUtils {

    public static String chooseService() {
        List<String> serverList = IdSdkConfig.getInstance().getServerList();
        StringBuilder url = new StringBuilder();
        if (serverList != null && serverList.size() == 1) {
            url.append(serverList.get(0));
        } else if (serverList != null && serverList.size() > 1) {
            Random r = new Random();
            url.append(serverList.get(r.nextInt(serverList.size())));
        }
        if (! url.toString().endsWith("/")) {
            url.append("/");
        }
        return url.toString();
    }

    public static String getUrl(MethodBaseEnum methodEnum) {
        return new StringBuilder(chooseService())
                .append(methodEnum.getMethod())
                .toString();
    }

    public static Map<String,String> getHeader() {
        Map<String,String> header = Maps.newHashMap();
        header.put(UrlHeaderConstants.ID_TOKEN, IdSdkConfig.getInstance().getBizToken());
        return header;
    }
}
